package com.ylzinfo.answer.controller;

import cn.hutool.core.io.FileUtil;
import com.ylzinfo.answer.bean.AnswerCardBean;
import com.ylzinfo.answer.bean.AnswerLogBean;
import com.ylzinfo.answer.bean.DicCodeBean;
import com.ylzinfo.answer.dao.jpa.AnswerCardBeanJpa;
import com.ylzinfo.answer.entity.AnswerCard;
import com.ylzinfo.answer.parser.service.ParserService;
import com.ylzinfo.answer.service.AnswerCardService;
import com.ylzinfo.answer.service.AnswerService;
import com.ylzinfo.answer.service.DicService;
import com.ylzinfo.answer.service.SignInService;
import com.ylzinfo.answer.vo.ErrorSearchVo;
import com.ylzinfo.answer.vo.SearchVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.security.Principal;
import java.util.*;

@Controller
@RequestMapping("/answer")
public class AnswerController {

    @Autowired
    private AnswerService answerService;

    @Autowired
    private AnswerCardBeanJpa answerCardBeanJpa;

    @Autowired
    private AnswerCardService answerCardService;

    @Autowired
    private DicService dicService;

    @Autowired
    private ParserService parserService;

    @Autowired
    private SignInService signInService;

    @RequestMapping("/log/list")
    public String listLog(Map<String, Object> map) {

        List<DicCodeBean> answerTypeList = dicService.findAllByCode("ANSWER_TYPE");

        map.put("answerTypeList", answerTypeList);

        return "answer/log_list";
    }

    @RequestMapping("/log/listAnswerLogByParam")
    @ResponseBody
    public Map<String, Object> listAnswerLogByParam(
            @RequestParam(value = "pn", defaultValue = "1") Integer pn,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            SearchVo searchVo
    ) {

        return answerService.listAnswerLogByParam(pn, pageSize, searchVo);
    }

    @RequestMapping("/list")
    public String list(Map<String, Object> map) {

//        List<DicCodeBean> answerTypeList = dicService.findAllByCode("ANSWER_TYPE");
        List<DicCodeBean> answerTypeList = dicService.findDicCode();

        map.put("answerTypeList", answerTypeList);

        return "answer/list";
    }

    @RequestMapping("/listAnswerCardByParam")
    @ResponseBody
    public Map<String, Object> listAnswerCardByParam(
            @RequestParam(value = "pn", defaultValue = "1") Integer pn,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            SearchVo searchVo
    ) {

        return answerService.listAnswerCardByParam(pn, pageSize, searchVo);
    }

    @RequestMapping("/log/batchDelAnswerLog")
    @ResponseBody
    public Map<String, Object> batchDelAnswerLog(
            @RequestParam("selectId") String selectId
    ) {
        Map<String, Object> dataMap = new HashMap<>();
        try {
            answerService.batchDelAnswerLog(selectId);
            dataMap.put("flag", true);
        } catch (Exception e) {
            e.printStackTrace();
            dataMap.put("flag", false);
            dataMap.put("errorMsg", e.getMessage());
        }

        return dataMap;
    }

    @RequestMapping("/batchDelAnswerCard")
    @ResponseBody
    public Map<String, Object> batchDelAnswerCard(
            @RequestParam("selectId") String selectId
    ) {
        Map<String, Object> dataMap = new HashMap<>();
        try {
            answerService.batchDelAnswerCard(selectId);
            dataMap.put("flag", true);
        } catch (Exception e) {
            e.printStackTrace();
            dataMap.put("flag", false);
            dataMap.put("errorMsg", e.getMessage());
        }

        return dataMap;
    }

    @RequestMapping("/study/{id}")
    public String study(Map<String, Object> map, @PathVariable("id") Long id) {
        AnswerCardBean answerCardBean = answerCardService.getOne(id);
        map.put("answerCardBean", answerCardBean);
        map.put("error", answerCardBean.getAnswerType());
        map.put("logType", "STUDY");
        return "answer/detail";
    }

    @RequestMapping("/createErrorAnswerCard")
    @ResponseBody
    public Map<String, Object> createErrorAnswerCard(
            @RequestParam("answerLogIdList") String answerLogIdList
    ) {
        Map<String, Object> dataMap = new HashMap<>();
        try {
            AnswerCardBean answerCardBean = answerService.errorStudy(Arrays.asList(answerLogIdList.split(",")));
            dataMap.put("flag", true);
            dataMap.put("answerCardBean", answerCardBean);
        } catch (Exception e) {
            e.printStackTrace();
            dataMap.put("flag", false);
            dataMap.put("errorMsg", e.getMessage());
        }

        return dataMap;
    }

    @RequestMapping("/saveAnswerLog")
    @ResponseBody
    public Map<String, Object> saveAnswerLog(
            Principal principal,
            @RequestBody AnswerLogBean answerLogBean
    ) {
        Map<String, Object> dataMap = new HashMap<>();
        answerLogBean.setUserName(principal.getName());
        try {
            answerService.saveAnswerLog(answerLogBean);
            dataMap.put("flag", true);
        } catch (Exception e) {
            e.printStackTrace();
            dataMap.put("flag", false);
            dataMap.put("errorMsg", e.getMessage());
        }
        return dataMap;
    }

    @RequestMapping("/uploadAnswer")
    public String uploadAnswer() {

        return "answer/upload_answer";
    }

    @RequestMapping("/test")
    @ResponseBody
    public String test() {
        return "test";
    }

    @RequestMapping("/lookAnswerByFile")
    public String lookAnswerByFile(Map<String, Object> map, @RequestParam("filePath") String filePath) throws Exception {

        List<AnswerCardBean> answerCardBeanList = parserService.preview(new File(filePath));

        map.put("answerCardBean", answerCardBeanList.get(0));
        map.put("byFile", "1");

        return "answer/detail";
    }

    @RequestMapping("/uploadFile")
    @ResponseBody
    public Map<String, Object> uploadFile(MultipartFile file) throws Exception {
        String filePath = String.format("D:/answer/%s.%s", UUID.randomUUID().toString(), file.getOriginalFilename().split("\\.")[1]);
        File testFile = new File(filePath);
        file.transferTo(testFile);

        Map<String, Object> dataMap = new HashMap<>();

        dataMap.put("code", 0);
        dataMap.put("filePath", filePath);

        return dataMap;
    }

    @RequestMapping("/saveAnswerByFile")
    @ResponseBody
    public Map<String, Object> saveAnswerByFile(@RequestParam("filePath") String filePath) {
        Map<String, Object> dataMap = new HashMap<>();
        try {
            List<AnswerCardBean> answerCardBean = parserService.insert(new File(filePath));
            dataMap.put("flag", true);
            dataMap.put("answerCardBeanList", answerCardBean);
        } catch (Exception e) {
            e.printStackTrace();
            dataMap.put("flag", false);
            dataMap.put("errorMsg", e.getMessage());
        }

        return dataMap;
    }

    @GetMapping("/test/{cardId}")
    public String test(@PathVariable long cardId, ModelMap modelMap,Principal principal) {
        AnswerCard answerCardBean = answerService.test(cardId);
        modelMap.put("answerCardBean", answerCardBean);
        modelMap.put("error", answerCardBean.getAnswerType());
        modelMap.addAttribute("isSignIn",signInService.getSignInByUserName(principal.getName()));
        modelMap.put("logType", "TEST");
        return "answer/detail";
    }

    @RequestMapping("/error/list")
    public String errorList(){
        return "answer/error_list";
    }

    /**
     * 获取错题集数据列表
     * @param pn
     * @param pageSize
     * @param errorSearchVo
     * @return
     */
    @RequestMapping("/listError")
    @ResponseBody
    public Map<String, Object> listError(
            @RequestParam(value = "pn", defaultValue = "1") Integer pn,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            ErrorSearchVo errorSearchVo
    ) {
        return answerService.findErrorList(pn,pageSize,errorSearchVo);
    }

    @GetMapping("/error/{selectId}")
    public String error(@PathVariable long selectId, Map<String, Object> map) {
        AnswerCardBean answerCardBean = answerCardService.getOne(selectId);
        map.put("answerCardBean", answerCardBean);
        map.put("error", answerCardBean.getAnswerType());
        map.put("logType", "ERROR");
        return "answer/detail";
    }

    @GetMapping("/downloadTemplate")
    public void downladTemplate(HttpServletResponse response) throws IOException {
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" +
                new String("试卷模板.docx".getBytes(), "ISO8859-1"));
//        FileUtil.writeToStream(ResourceUtil.getResource("/file/test1.docx").getPath(), response.getOutputStream());
        FileUtil.writeToStream("/file/test1.docx", response.getOutputStream());
    }

}
